package cn.wolfcode.education.service.impl;

import cn.wolfcode.education.domain.Permission;
import cn.wolfcode.education.domain.Role;
import cn.wolfcode.education.mapper.RoleMapper;
import cn.wolfcode.education.query.QueryObject;
import cn.wolfcode.education.service.IRoleService;
import cn.wolfcode.education.util.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class RoleServiceImpl implements IRoleService {

    @Autowired
    private RoleMapper roleMapper;

    public PageResult listAll(QueryObject qo) {
       Integer total =  roleMapper.queryForCount(qo);
       if(total == 0){
           return new PageResult();
       }
       List<Role> rows = roleMapper.queryForList(qo);
        return new PageResult(total,rows);
    }

    public void save(Role role) {
        roleMapper.insert(role);
        for(Permission permission : role.getPermissions()){
        roleMapper.insertRelationWithPermission(role.getId(),permission.getId());
        }
    }

    public void update(Role role) {
        roleMapper.updateByPrimaryKey(role);
        roleMapper.deleteRelationWithPermission(role.getId());
        for(Permission permission : role.getPermissions()){
            roleMapper.insertRelationWithPermission(role.getId(),permission.getId());
        }
    }

    public List<Role> list() {
        return roleMapper.selectAll();
    }

    public List<Long> listRoleByEmployeeId(Long employeeId) {
        return roleMapper.listRoleByEmployeeId(employeeId);
    }
}